from django.core.validators import RegexValidator
import random

from django.core.mail import send_mail
from django.core.validators import RegexValidator
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework import serializers
from rest_framework.views import APIView

from APP.current import models
from APP.current.models import Current, PersonalInformation


# Create your views here.

class LoginSerializers(serializers.ModelSerializer):
    phone = serializers.CharField(
        label='手机号',
        validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ]
    )
    email = serializers.CharField(
        label="QQ邮箱",
        validators=[RegexValidator(r'^[1-9]\d{4,10}@qq\.com$', '邮箱输入错误'),]
    )
    password = serializers.CharField(
        label="密码",
        validators=[RegexValidator(r'^(?=.*\d)(?=.*[A-Za-z]).{8,}$'), '密码格式错误']
    )
    class Meta:
        model = Current
        fields = "__all__"

class LoginView(APIView):
    def get(self,request):
        return render(request,'email.html')

    def post(self,request):
        user = LoginSerializers(data=request.data)
        if user.is_valid():
            return JsonResponse(msg='登录成功', code=100,
                                data={'token': user.context.get('token'),
                                      'username': user.context.get('username').username})
        else:
            return JsonResponse(msg=user.errors, code=101)

class EmailView(APIView):
    def post(self, request):
        email = request.data.get('email')  # Use 'data' instead of 'POST' for DRF.
        verification_code = self.generate_verification_code()
        # Store the verification code in the session.
        request.session['rand_code'] = verification_code
        try:
            self.send_verification_email(email, verification_code)
            print(verification_code)
            request.session[email]= verification_code
            request.session.set_expiry(1 * 1 * 3600)
            return JsonResponse({"message": "验证码发送成功"})
        except Exception as e:
            print(str(e))
            return JsonResponse({"message": "验证码发送失败"})

    def generate_verification_code(self):
        code_list = [str(i) for i in range(10)]  # 0-9 digits
        code_list.extend([chr(i) for i in range(65, 91)])  # 'A' to 'Z'
        code_list.extend([chr(i) for i in range(97, 123)])  # 'a' to 'z'
        myslice = random.sample(code_list, 6)
        return ''.join(myslice)

    def send_verification_email(self, email, verification_code):
        subject = '教务系统找回密码'
        message = f'验证码1分钟内有效验：{verification_code}'
        from_email = '2979927958@qq.com'
        recipient_list = [email]

        res = send_mail(subject, message, from_email, recipient_list)
        if res != 1:
            raise Exception('验证码发送失败')
class EmailRegisterView(APIView):
    def get(self,request):
        pass
    def post(self,request):
        email = request.data.get("email")
        code = request.data.get("code")
        if code == request.session[email]:
            serializer = LoginSerializers(data=request.data) # 反序列话
            if serializer.is_valid():  # 对数据进行校验
                # 数据通过校验后，将数据插入到数据库中
                Current.objects.create(**serializer.validated_data)
                return JsonResponse({"message": "创建成功","data":serializer.data})
        return JsonResponse({"message": serializer.errors})
    def put(self,request,email):
        update = Current.objects.get(email=email)
        serializer = LoginSerializers(instance=update, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"data": "更新成功"})
        return JsonResponse({"data": serializer.errors})
    def delete(self,request):
        pass

class PhoneRegisterView(APIView):
    def get(self,request):
        pass
    def post(self,request):
        email = request.data.get("phone")
        code = request.data.get("code")
        if code == request.session[email]:
            serializer = LoginSerializers(data=request.data)
            if serializer.is_valid():  # 对数据进行校验
                # 数据通过校验后，将数据插入到数据库中
                Current.objects.create(**serializer.validated_data)
                return JsonResponse({"message": "创建成功","data":serializer.data})
        return JsonResponse({"message": serializer.errors})
    def put(self,request,email):
        update = Current.objects.get(email=email)
        serializer = LoginSerializers(instance=update, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"data": "更新成功"})
        return JsonResponse({"data": serializer.errors})
    def delete(self,request):
        pass




